package com.yubest;

import java.util.ArrayList;
import java.util.List;

/**
 * 给你一个 m x n 的矩阵 board ，由若干字符 'X' 和 'O' ，找到所有被 'X' 围绕的区域，并将这些区域里所有的 'O' 用 'X' 填充。
 *  
 * <p>
 * 示例 1：[图片] img/0130.jpg
 * <p>
 * <p>
 * 输入：board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
 * 输出：[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
 * 解释：被围绕的区间不会存在于边界上，换句话说，任何边界上的 'O' 都不会被填充为 'X'。 任何不在边界上，或不与边界上的 'O' 相连的 'O' 最终都会被填充为 'X'。如果两个元素在水平或垂直方向相邻，则称它们是“相连”的。
 * 示例 2：
 * <p>
 * 输入：board = [["X"]]
 * 输出：[["X"]]
 *  
 * <p>
 * 提示：
 * <p>
 * m == board.length
 * n == board[i].length
 * 1 <= m, n <= 200
 * board[i][j] 为 'X' 或 'O'
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/surrounded-regions
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 *
 * @Author hweiyu
 * @Description
 * @Date 2021/12/15 17:36
 */
public class P0130 {

    public static void main(String[] args) {
        new Solution130().solve(new char[][]{{'X', 'X', 'X', 'X'}, {'X', 'O', 'O', 'X'}, {'X', 'X', 'O', 'X'}, {'X', 'O', 'X', 'X'}});
    }
}

class Solution130 {

    public void solve(char[][] board) {
        int m = board.length;
        int n = board[0].length;
        boolean[][] record = new boolean[m][n];
        //先标记边界中所有的 'O'，然后从边界中的'O'开始递归遍历相邻的项
        for (int i = 0; i < m; i++) {
            if ('O' == board[i][0]) {
                record[i][0] = true;
                solve(board, i, 0, true, record);
            }
            if ('O' == board[i][n - 1]) {
                record[i][n - 1] = true;
                solve(board, i, n - 1, true, record);
            }
        }
        for (int i = 0; i < n; i++) {
            if ('O' == board[0][i]) {
                record[0][i] = true;
                solve(board, 0, i, true, record);
            }
            if ('O' == board[m - 1][i]) {
                record[m - 1][i] = true;
                solve(board, m - 1, i, true, record);
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == 'O' && !record[i][j]) {
                    board[i][j] = 'X';
                }
            }
        }
    }

    private void solve(char[][] board, int i, int j, boolean isStart, boolean[][] record) {
        if (i < 0 || j < 0 || i >= board.length || j >= board[i].length) {
            return;
        }
        if (!isStart && record[i][j]) {
            return;
        }
        if (board[i][j] != 'O') {
            return;
        }
        record[i][j] = true;
        solve(board, i, j + 1, false, record);
        solve(board, i, j - 1, false, record);
        solve(board, i + 1, j, false, record);
        solve(board, i - 1, j, false, record);
    }

}
